import React from 'react';
import { 
  Box,
  Menu,
  MenuItem,
  ListItemIcon 
} from '@mui/material';
import { Person as UserIcon } from '@mui/icons-material';
import { Group as UsersIcon } from '@mui/icons-material';
import { AttachMoney as MoneyIcon } from '@mui/icons-material';
import GitHubIcon from '@mui/icons-material/GitHub';
import LoginIcon from '@mui/icons-material/Login';
import LogoutIcon from '@mui/icons-material/Logout';
import { SimpleTreeView } from '@mui/x-tree-view/SimpleTreeView';
import { TreeItem } from '@mui/x-tree-view/TreeItem';
import { useTranslation } from 'react-i18next';

// Import UI components for subscription, payment methods, and payment history
import PaymentHistoryUserInterface from 'components/ui/PaymentHistoryUserInterface';
import PaymentMethodsUserInterface from 'components/ui/PaymentMethodsUserInterface';
import SubscriptionUserInterface from 'components/ui/SubscriptionUserInterface';

// Define the expanded TreeItem styles to match the main styleTreeView format
const expandedTreeItemStyle = (isXs, darkMode) => ({
  '& .MuiTreeItem-label': {
    textAlign: 'right',
    fontFamily: "'Roboto Condensed', sans-serif",
    fontWeight: 'bold',
    fontSize: '200%', // Always use isXs=true value
    color: darkMode ? 'white' : 'black',
    cursor: 'pointer',
  }
});

// Extract styles from HomePage content to reuse across all SimpleTreeView components
const getSimpleTreeViewStyles = (isXs, darkMode) => ({
  // Always use isXs=true styling
  width: 'auto', // isXs=true doesn't specify width
  display: 'flex', 
  flexDirection: 'column',
  '& .MuiTreeItem-content': {
    flexDirection: 'row-reverse',
    justifyContent: 'flex-start',
    padding: '4px 0', // isXs=true value
    marginBottom: '4px', // isXs=true value
  },
  '& .MuiTreeItem-label': {
    textAlign: 'right',
    fontFamily: "'Roboto Condensed', sans-serif",
    fontWeight: 'bold',
    fontSize: '200%', // isXs=true value
    color: darkMode ? 'white' : 'black',
    cursor: 'pointer',
  },
  '& .MuiTreeItem-iconContainer': {
    display: 'none', // Hide the icon container completely
  }
});

// Define the Menu component structure as a constant to be reused
export const MenuComponent = ({ 
  menuAnchorEl, 
  isMenuOpen, 
  handleMenuClose, 
  navigatePage, 
  navigateOpen, 
  user, 
  contextDarkMode, 
  theme 
}) => {
  return (
    <Menu
      id="menu-dropdown"
      anchorEl={menuAnchorEl}
      open={isMenuOpen}
      onClose={handleMenuClose}
      MenuListProps={{
        'aria-labelledby': 'menu-button',
      }}
      PaperProps={{
        elevation: 3,
        sx: {
          mt: 1.5,
          borderRadius: '10px',
          backgroundColor: contextDarkMode ? theme.palette.grey[900] : 'white',
        }
      }}
      transformOrigin={{ horizontal: 'right', vertical: 'top' }}
      anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
    >
      {/* GitHub Links */}
      <MenuItem onClick={() => navigatePage('https://github.com/startersaas/startersaas-backend-go-api-main.git')}>
        <ListItemIcon>
          <GitHubIcon fontSize="small" />
        </ListItemIcon>
        Go API
      </MenuItem>
      <MenuItem onClick={() => navigatePage('https://github.com/startersaas/startersaas-backend-node-api-main.git')}>
        <ListItemIcon>
          <GitHubIcon fontSize="small" />
        </ListItemIcon>
        Node API
      </MenuItem>
      <MenuItem onClick={() => navigatePage('https://github.com/startersaas/startersaas-frontend-react-spa.git')}>
        <ListItemIcon>
          <GitHubIcon fontSize="small" />
        </ListItemIcon>
        React API
      </MenuItem>
      
      {/* Login/Logout based on user authentication */}
      {user ? (
        <MenuItem onClick={() => navigateOpen('/auth/logout')}>
          <ListItemIcon>
            <LogoutIcon fontSize="small" />
          </ListItemIcon>
          Logout
        </MenuItem>
      ) : (
        <MenuItem onClick={() => navigateOpen('/auth/login')}>
          <ListItemIcon>
            <LoginIcon fontSize="small" />
          </ListItemIcon>
          Login
        </MenuItem>
      )}
    </Menu>
  );
};

// Create InfoBox components that can be reused
export const SingleInfoBox = ({ isXs, darkMode, admin = false }) => {
  return (
    <Box sx={{ 
      p: 2,
      border: darkMode ? '1px solid #30363d' : '1px solid #d0d7de',
      borderRadius: '6px',
      backgroundColor: darkMode ? '#0d1117' : '#f6f8fa',
      fontSize: '0.9rem', // Always use isXs=true value
      margin: 0
    }}>
      <Box>
        This is your dashboard panel, where you can use the links above to access Subscriber features for managing your User accounts, Team settings, and Plan details. If you have Developer access, you'll also find tools and settings tailored for building integrations and customizing your experience. Workspaces offer shared tools commonly found in CRM software, such as contact management, activity tracking, and collaboration features. Or use the Quick Links here to access Documentation and API examples to help you get started faster.
      </Box>

      {admin && (
        <Box sx={{ 
          display: 'flex', 
          flexDirection: 'column', 
          alignItems: 'center',
          justifyContent: 'center',
          gap: 2,
          mt: 2
        }}>
          <SubscriptionUserInterface 
            buttonText="Subscription" 
            simpleButton={true} 
          />
          <PaymentMethodsUserInterface 
            buttonText="Payment" 
            simpleButton={true} 
          />
          <PaymentHistoryUserInterface 
            buttonText="History" 
            simpleButton={true} 
          />
        </Box>
      )}
    </Box>
  );
};

export const GridInfoBox = ({ darkMode, admin = false }) => {
  // Set font size directly - no ternary needed since this component is only used in non-xs view
  const fontSize = '0.6rem';
  
  // Create base styles for grid items
  const gridItemStyles = {
    flex: '1 1 33.33%',
    p: 2,
    border: darkMode ? '1px solid #30363d' : '1px solid #d0d7de',
    borderRadius: '6px',
    backgroundColor: darkMode ? '#0d1117' : '#f6f8fa',
    fontSize: fontSize,
    margin: 0
  };
  
  // Create base styles for admin buttons container
  const adminButtonsContainerStyles = {
    display: 'flex', 
    flexDirection: 'column', 
    alignItems: 'center',
    justifyContent: 'center',
    gap: 2,
    mt: 2
  };
  
  return (
    <Box sx={{ 
      display: 'flex',
      flexDirection: 'row',
      gap: 2,
      width: '100%'
    }}>
      {/* Grid Item 1 */}
      <Box sx={gridItemStyles}>
        <Box>
          This is your dashboard panel, where you can use the links above to access Subscriber features for managing your User accounts, Team settings, and Plan details. If you have Developer access, you'll also find tools and settings tailored for building integrations and customizing your experience.
        </Box>

        {admin && (
          <Box sx={adminButtonsContainerStyles}>
            <SubscriptionUserInterface 
              buttonText="Subscription" 
              simpleButton={true} 
            />
          </Box>
        )}
      </Box>
      
      {/* Grid Item 2 */}
      <Box sx={gridItemStyles}>
        <Box>
          This is your dashboard panel, where you can use the links above to access Subscriber features for managing your User accounts, Team settings, and Plan details. If you have Developer access, you'll also find tools and settings tailored for building integrations and customizing your experience.
        </Box>

        {admin && (
          <Box sx={adminButtonsContainerStyles}>
            <PaymentMethodsUserInterface 
              buttonText="Payment" 
              simpleButton={true} 
            />
          </Box>
        )}
      </Box>
      
      {/* Grid Item 3 */}
      <Box sx={gridItemStyles}>
        <Box>
          This is your dashboard panel, where you can use the links above to access Subscriber features for managing your User accounts, Team settings, and Plan details. If you have Developer access, you'll also find tools and settings tailored for building integrations and customizing your experience.
        </Box>

        {admin && (
          <Box sx={adminButtonsContainerStyles}>
            <PaymentHistoryUserInterface 
              buttonText="History" 
              simpleButton={true} 
            />
          </Box>
        )}
      </Box>
    </Box>
  );
};

// Create a content layout component that can be reused across different content components
export const ContentLayout = ({ 
  children, // This is the treeView content
  isXs, 
  placeBefore, 
  darkMode,
  layout = '',  // Updated to default empty string instead of boolean
  admin = false // New prop for admin functionality
}) => {
  // Determine which info box to show based on layout and screen size
  let infoBox = null;
  
  if (!layout) {
    // Always use the SingleInfoBox (isXs=true behavior)
    infoBox = <SingleInfoBox isXs={isXs} darkMode={darkMode} admin={admin} />;
  } else if (layout === 'public') {
    // When layout is "public" - always render SingleInfoBox
    infoBox = <SingleInfoBox isXs={isXs} darkMode={darkMode} admin={admin} />;
  }
  // For other layout values, infoBox remains null (no info box shown)
  
  return (
    <Box sx={{ 
      p: 2, // Always use isXs=true value
      fontSize: '0.85rem', // Always use isXs=true value
      color: darkMode ? '#e6edf3' : '#24292f', 
      lineHeight: 1.4, // Always use isXs=true value
      // No flex properties (isXs=true behavior)
    }}>
      {placeBefore ? (
        <>
          {infoBox}
          {children}
        </>
      ) : (
        <>
          {children}
          {infoBox}
        </>
      )}
    </Box>
  );
};

export const HomePageContent = ({ isXs, placeBefore, darkMode, navigateOpen, navigatePage, layout = '' }) => {
  // State for menu handling
  const [menuAnchorEl, setMenuAnchorEl] = React.useState(null);
  const isMenuOpen = Boolean(menuAnchorEl);
  const theme = { palette: { grey: { 900: '#1e1e1e' } } }; // Simple theme object
  
  const handleMenuOpen = (event) => {
    setMenuAnchorEl(event.currentTarget);
  };
  
  const handleMenuClose = () => {
    setMenuAnchorEl(null);
  };
  
  // Handle Developer or API Reference click
  const handleDevelopersClick = (event) => {
    // Prevent the default TreeItem behavior
    event.stopPropagation();
    // Open the menu
    handleMenuOpen(event);
  };
  
  return (
    <>
      <SimpleTreeView
        sx={getSimpleTreeViewStyles(isXs, darkMode)}
        defaultExpanded={['5']}
      >
        <TreeItem itemId="1" label="Login" onClick={() => navigateOpen('/auth/login')} />
        <TreeItem itemId="2" label="Signup" onClick={() => navigateOpen('/auth/register')} />
        <TreeItem itemId="3" label="Developers" onClick={handleDevelopersClick} />
        <TreeItem itemId="4" label="Subscribers" onClick={() => navigateOpen('/subscribers')} />
        <TreeItem itemId="5" label="Social">
          <TreeItem 
            itemId="5-1" 
            label="Instagram" 
            onClick={() => navigatePage('https://www.instagram.com/part_of_the_skwad/')}
            sx={expandedTreeItemStyle(isXs, darkMode)}
          />
          <TreeItem 
            itemId="5-2" 
            label="LinkedIn" 
            onClick={() => navigatePage('https://www.linkedin.com/in/nathaniel-s-276515334?trk=contact-info')}
            sx={expandedTreeItemStyle(isXs, darkMode)}
          />
          <TreeItem 
            itemId="5-3" 
            label="Facebook" 
            onClick={() => navigatePage('https://m.facebook.com/Partoftheskwad/')}
            sx={expandedTreeItemStyle(isXs, darkMode)}
          />
        </TreeItem>
      </SimpleTreeView>
      
      {/* Menu that appears when clicking Developers */}
      <MenuComponent 
        menuAnchorEl={menuAnchorEl}
        isMenuOpen={isMenuOpen}
        handleMenuClose={handleMenuClose}
        navigatePage={navigatePage}
        navigateOpen={navigateOpen}
        user={null} // No user in this context
        contextDarkMode={darkMode}
        theme={theme}
      />
    </>
  );
};

export const AdminContent = ({ isXs, placeBefore, darkMode, navigateOpen, navigatePage, layout = '' }) => {
  const { t } = useTranslation();
  
  // State for menu handling
  const [menuAnchorEl, setMenuAnchorEl] = React.useState(null);
  const isMenuOpen = Boolean(menuAnchorEl);
  const theme = { palette: { grey: { 900: '#1e1e1e' } } }; // Simple theme object
  
  const handleMenuOpen = (event) => {
    setMenuAnchorEl(event.currentTarget);
  };
  
  const handleMenuClose = () => {
    setMenuAnchorEl(null);
  };
  
  // Handle API Reference click
  const handleApiReferenceClick = (event) => {
    // Prevent the default TreeItem behavior
    event.stopPropagation();
    // Open the menu
    handleMenuOpen(event);
  };
  
  // Always use isXs=true values
  const iconSize = 'default';
  const iconMargin = 1;
  
  const treeView = (
    <>
      <SimpleTreeView
        sx={getSimpleTreeViewStyles(isXs, darkMode)}
      >
        <TreeItem 
          itemId="users" 
          label={
            <Box sx={{ display: 'flex', alignItems: 'center' }}>
              <UserIcon sx={{ mr: iconMargin, fontSize: iconSize }} />
              {t("privateLayout.users")}
            </Box>
          }
          onClick={() => navigateOpen('/users')}
        />
        <TreeItem 
          itemId="teams" 
          label={
            <Box sx={{ display: 'flex', alignItems: 'center' }}>
              <UsersIcon sx={{ mr: iconMargin, fontSize: iconSize }} />
              TEAMS
            </Box>
          }
          onClick={() => navigateOpen('/teams')}
        />
        <TreeItem 
          itemId="plan" 
          label={
            <Box sx={{ display: 'flex', alignItems: 'center' }}>
              <MoneyIcon sx={{ mr: iconMargin, fontSize: iconSize }} />
              {t("dashboardPage.plan").toUpperCase()}
            </Box>
          }
          onClick={() => navigateOpen('/plan')}
        />
        <TreeItem 
          itemId="api-reference" 
          label="API Reference"
          onClick={handleApiReferenceClick}
        />
      </SimpleTreeView>
      
      {/* Menu that appears when clicking API Reference */}
      <MenuComponent 
        menuAnchorEl={menuAnchorEl}
        isMenuOpen={isMenuOpen}
        handleMenuClose={handleMenuClose}
        navigatePage={navigatePage}
        navigateOpen={navigateOpen}
        user={null} // No user in this context
        contextDarkMode={darkMode}
        theme={theme}
      />
    </>
  );
  
  return (
    <ContentLayout 
      isXs={isXs} 
      placeBefore={placeBefore} 
      darkMode={darkMode} 
      layout={layout}
      admin={true} // Admin is true for this component
    >
      {treeView}
    </ContentLayout>
  );
};

export const UserContent = ({ isXs, placeBefore, darkMode, navigateOpen, navigatePage, layout = '' }) => {
  // State for menu handling
  const [menuAnchorEl, setMenuAnchorEl] = React.useState(null);
  const isMenuOpen = Boolean(menuAnchorEl);
  const theme = { palette: { grey: { 900: '#1e1e1e' } } }; // Simple theme object
  
  const handleMenuOpen = (event) => {
    setMenuAnchorEl(event.currentTarget);
  };
  
  const handleMenuClose = () => {
    setMenuAnchorEl(null);
  };
  
  // Handle API Reference or Developers click
  const handleSpecialClick = (event) => {
    // Prevent the default TreeItem behavior
    event.stopPropagation();
    // Open the menu
    handleMenuOpen(event);
  };
  
  const treeView = (
    <>
      <SimpleTreeView 
        defaultExpanded={['1', '2', '3', '4']}
        sx={getSimpleTreeViewStyles(isXs, darkMode)}
      >
        <TreeItem itemId="1" label="Quick Links">
          <TreeItem itemId="1-1" label="Dashboard" sx={expandedTreeItemStyle(isXs, darkMode)} onClick={() => navigateOpen('/dashboard')} />
          <TreeItem itemId="1-2" label="Account Settings" sx={expandedTreeItemStyle(isXs, darkMode)} onClick={() => navigateOpen('/account')} />
          <TreeItem itemId="1-3" label="Notifications" sx={expandedTreeItemStyle(isXs, darkMode)} onClick={() => navigateOpen('/notifications')} />
          <TreeItem itemId="1-4" label="Help Center" sx={expandedTreeItemStyle(isXs, darkMode)} onClick={() => navigateOpen('/help')} />
        </TreeItem>
        
        <TreeItem itemId="2" label="Documentation">
          <TreeItem itemId="2-1" label="Getting Started" sx={expandedTreeItemStyle(isXs, darkMode)} onClick={() => navigateOpen('/docs/getting-started')} />
          <TreeItem itemId="2-2" label="API Reference" sx={expandedTreeItemStyle(isXs, darkMode)} onClick={handleSpecialClick} />
          <TreeItem itemId="2-3" label="User Guides" sx={expandedTreeItemStyle(isXs, darkMode)} onClick={() => navigateOpen('/docs/guides')} />
          <TreeItem itemId="2-4" label="Tutorials" sx={expandedTreeItemStyle(isXs, darkMode)} onClick={() => navigateOpen('/docs/tutorials')} />
        </TreeItem>
        
        <TreeItem itemId="3" label="Resources">
          <TreeItem itemId="3-1" label="Templates" sx={expandedTreeItemStyle(isXs, darkMode)} onClick={() => navigateOpen('/resources/templates')} />
          <TreeItem itemId="3-2" label="Examples" sx={expandedTreeItemStyle(isXs, darkMode)} onClick={() => navigateOpen('/resources/examples')} />
          <TreeItem itemId="3-3" label="Best Practices" sx={expandedTreeItemStyle(isXs, darkMode)} onClick={() => navigateOpen('/resources/best-practices')} />
          <TreeItem itemId="3-4" label="Tools" sx={expandedTreeItemStyle(isXs, darkMode)} onClick={() => navigateOpen('/resources/tools')} />
          <TreeItem itemId="3-5" label="Community Forum" sx={expandedTreeItemStyle(isXs, darkMode)} onClick={() => navigateOpen('/community')} />
        </TreeItem>
        
        <TreeItem itemId="4" label="Workspace">
          <TreeItem itemId="4-1" label="Contacts" sx={expandedTreeItemStyle(isXs, darkMode)} onClick={() => navigateOpen('/workspace/contacts')} />
          <TreeItem itemId="4-2" label="Activities" sx={expandedTreeItemStyle(isXs, darkMode)} onClick={() => navigateOpen('/workspace/activities')} />
          <TreeItem itemId="4-3" label="Tasks" sx={expandedTreeItemStyle(isXs, darkMode)} onClick={() => navigateOpen('/workspace/tasks')} />
          <TreeItem itemId="4-4" label="Reports" sx={expandedTreeItemStyle(isXs, darkMode)} onClick={() => navigateOpen('/workspace/reports')} />
          <TreeItem itemId="4-5" label="Team Collaboration" sx={expandedTreeItemStyle(isXs, darkMode)} onClick={() => navigateOpen('/workspace/collaboration')} />
        </TreeItem>
        
        <TreeItem itemId="5" label="Developers" onClick={handleSpecialClick} />
      </SimpleTreeView>
      
      {/* Menu that appears when clicking API Reference or Developers */}
      <MenuComponent 
        menuAnchorEl={menuAnchorEl}
        isMenuOpen={isMenuOpen}
        handleMenuClose={handleMenuClose}
        navigatePage={navigatePage}
        navigateOpen={navigateOpen}
        user={null} // No user in this context
        contextDarkMode={darkMode}
        theme={theme}
      />
    </>
  );

  return (
    <ContentLayout 
      isXs={isXs} 
      placeBefore={placeBefore} 
      darkMode={darkMode} 
      layout={layout}
      admin={false} // Admin is false for UserContent
    >
      {treeView}
    </ContentLayout>
  );
};